今天的主題為函式。
函式,是由一群程式碼組合而成。通常我們在寫特定的功能時,就會使用函式去包裝所使用到的程式碼。
我們可以把函式想像成一個置物箱,每個函式都會有一個名稱
,就像每個置物箱都會有一個編號一樣。
使用函式時可以把一些參數
傳入,如同置物箱可以放入東西一樣。
函式會執行一些特定的任務,執行完畢後將結果返回,如同我們將物品放入置物箱,置物箱會執行保存物品這項任務,任務結束後將物品返回。
C
#include <stdio.h>
int main() {
int number1 = 1, number2 = 2, number3 = 3, number4 = 4, number5 = 5;
number1 += 10;
number2 += 10;
number3 += 10;
number4 += 10;
number5 += 10;
printf("%d\n", number1);
printf("%d\n", number2);
printf("%d\n", number3);
printf("%d\n", number4);
printf("%d\n", number5);
return 0;
}
以上程式碼有許多重複使用的地方,我們可以將其寫成函式,如下:
#include <stdio.h>
int addTen(int number) {
return number + 10;
}
int main() {
int number1 = 1, number2 = 2, number3 = 3, number4 = 4, number5 = 5;
printf("%d\n", addTen(number1));
printf("%d\n", addTen(number2));
printf("%d\n", addTen(number3));
printf("%d\n", addTen(number4));
printf("%d\n", addTen(number5));
return 0;
}
輸出結果:
11
12
13
14
15
Python
number1, number2, number3, number4, number5 = 1, 2, 3, 4, 5
number1 += 10
number2 += 10
number3 += 10
number4 += 10
number5 += 10
print(number1)
print(number2)
print(number3)
print(number4)
print(number5)
以上程式可簡化為:
def addTen(number):
return number + 10
number1, number2, number3, number4, number5 = 1, 2, 3, 4, 5
print(addTen(number1))
print(addTen(number2))
print(addTen(number3))
print(addTen(number4))
print(addTen(number5))
輸出結果:
11
12
13
14
15
JavaScript
var number1 = 1, number2 = 2, number3 = 3, number4 = 4, number5 = 5;
number1 += 10;
number2 += 10;
number3 += 10;
number4 += 10;
number5 += 10;
console.log(number1);
console.log(number2);
console.log(number3);
console.log(number4);
console.log(number5);
以上程式可簡化成:
function addTen(number) {
return number + 10;
}
var number1 = 1, number2 = 2, number3 = 3, number4 = 4, number5 = 5;
console.log(addTen(number1));
console.log(addTen(number2));
console.log(addTen(number3));
console.log(addTen(number4));
console.log(addTen(number5));
輸出結果:
11
12
13
14
15